import { Channel, UserChannelResponse } from "@/types/data"
import { RootThunkAction } from "@/types/store"
import { http } from "@/utils/http"

import { ArticlesResponse } from "@/types/data"

const CHANNEL_KEY = "geek-channels"
export const getUserChannel = (): RootThunkAction => {
  return async (dispatch, getState) => {
    const {
      login: { token },
    } = getState()
    let userChannel: Channel[] = []

    if (token) {
      // 登录
      const res = (await http.get("/user/channels")) as UserChannelResponse
      const { channels } = res.data
      console.log("登录", channels)
      userChannel = channels
    } else {
      // 未登录
      const localChannels = JSON.parse(
        localStorage.getItem(CHANNEL_KEY) ?? "[]"
      ) as Channel[]

      if (localChannels.length > 0) {
        userChannel = localChannels

        // 有
        console.log("未登录，本地有", localChannels)
      } else {
        // 没有
        const res = (await http.get("/user/channels")) as UserChannelResponse
        const { channels } = res.data
        localStorage.setItem(CHANNEL_KEY, JSON.stringify(channels))
        console.log("未登录，本地没有", channels)
        userChannel = channels
      }
    }
    dispatch({ type: "home/getUserChannel", payload: userChannel })
  }
}

export const getArticleList = (
  channel_id: number,
  timestamp: string,
  type: "replace" | "append"
): RootThunkAction => {
  return async (dispatch) => {
    const res = (await http.get("/articles", {
      params: {
        channel_id,
        timestamp,
      },
    })) as ArticlesResponse

    // 分发 action
    dispatch({
      type: "home/getChannelArticles",
      payload: {
        channelId: channel_id,
        data: res.data,
      },
      actionType: type,
    })
  }
}
